//
//  NearbySeachController.m
//  Zyachting
//
//  Created by hungnt47 on 17/10/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "NearbySeachController.h"
#import "ButtonCell1.h"
#import "SearchResultController.h"
#import "JSON.h"
#import <CoreLocation/CoreLocation.h>
@implementation NearbySeachController
@synthesize tableView;
@synthesize currentSelected;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [HUD setLabelText:@"Searching"];
    [self.view addSubview:HUD];
    [self.tableView setBackgroundView:nil];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    self.navigationItem.title = @"Search nearby";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark TableView DataSource Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.section) {
        case 0:         
            //normal
        {
            static NSString *CellIdentifier = @"Cell";
            
            UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            }
            switch (indexPath.row) {
                case 0:
                    cell.textLabel.text = @"1 Km";
                    break;
                case 1:
                    cell.textLabel.text = @"5 Km";
                    break;
                case 2:
                    cell.textLabel.text = @"10 Km";
                    break;
                default:
                    break;
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            if (indexPath.row == self.currentSelected) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            return cell;
        }
            break;
        case 1:
        {
            static NSString *CellIdentifier2 = @"ButtonCell1Identifier";
            
            ButtonCell1 *cell = (ButtonCell1 *)[tableView
                                              dequeueReusableCellWithIdentifier: CellIdentifier2];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ButtonCell1"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[ButtonCell1 class]])
                        cell = (ButtonCell1 *)oneObject;
            }
            [cell.searchBtn addTarget:self action:@selector(searchBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
            break;
        default:
            break;
    }
    return nil;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString* title = nil;
    switch (section) {
        case 0:
            //
            title = @"Select Distance";
            break;
        case 1:
            //
            title = @"";
            break;
            
        default:
            break;
    }
    return title;
}
#pragma mark -
#pragma mark TableView Delegate Method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        self.currentSelected = indexPath.row;
        [self.tableView reloadData];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 45.0f;
    }
    return 44;
}

#pragma mark -Action
-(IBAction)searchBtnTapped:(id)sender
{
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"The location service is turned off. In order to search nearby your location, you need to turn it on" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
        return;
    }
    [HUD show:YES];
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.z-yachting.com/ws/search.php"]];
    [request setDelegate:self];
    [request startAsynchronous];
}
-(AppDelegate*)appDelegate
{
    return (AppDelegate*)([[UIApplication sharedApplication] delegate]);
}
#pragma mark -ASIHTTPRequest Delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    NSArray* resultArray = [request.responseString JSONValue];
    NSMutableArray* filteredItems = [NSMutableArray array];
    float threadHold ;
    switch (self.currentSelected) {
        case 0:
            threadHold = 1000.0f;
            break;
        case 1:
            threadHold = 5000.0f;
            break;
        case 2:
            threadHold = 10000.0f;
            break;
        default:
            break;
    }
    for (int i =0; i< resultArray.count; i++) {
        NSDictionary* tmpDict = [resultArray objectAtIndex:i];
        double lat = [[tmpDict objectForKey:@"latitude"] doubleValue];
        double lon = [[tmpDict objectForKey:@"longitude"] doubleValue];
        CLLocation* location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
        if ([[self appDelegate].currentLocation distanceFromLocation:location] <= threadHold) {
            [filteredItems addObject:tmpDict];
        }
        
    }
    SearchResultController* searchResult = [[SearchResultController alloc] initWithNibName:@"SearchResultController" bundle:nil];
    [searchResult setItems:filteredItems];
    [self.navigationController pushViewController:searchResult animated:YES];
    [searchResult release];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Connection Fail. Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
@end
